package com.tyut.musicdreamer.framework.starter.storage.task;

import com.tyut.musicdreamer.framework.starter.storage.model.StorageClass;
import com.tyut.musicdreamer.framework.starter.storage.service.StorageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 存储类别更新定时任务
 * 根据文件访问频率自动调整存储类别
 */
@Component
@Slf4j
public class StorageClassUpdateTask extends BaseStorageClassUpdateTask {

    public StorageClassUpdateTask(StorageService storageService) {
        super(storageService);
    }
    
    /**
     * 每天凌晨2点执行存储类别更新
     */
    @Override
    @Scheduled(cron = "0 0 2 * * ?")
    public void updateStorageClass() {
        log.info("开始执行存储类别更新任务，共有{}个对象需要分析", accessCounter.size());
        
        accessCounter.forEach((objectKey, accessCount) -> {
            try {
                // 根据访问频率确定存储类别
                StorageClass targetClass = determineStorageClass(accessCount);
                log.info("对象[{}]访问量({}), 使用存储类别[{}]", objectKey, accessCount, targetClass);
                
                // 更新存储类别
                updateObjectStorageClass(objectKey, targetClass);
            } catch (Exception e) {
                log.error("更新对象[{}]存储类别失败", objectKey, e);
            }
        });
        
        // 清空计数器，准备下一个周期
        accessCounter.clear();
        log.info("存储类别更新任务完成");
    }
} 